﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using JavaScriptSupport;

namespace jsMinDesktop
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Perform minify javascript files.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnPerform_Click(object sender, EventArgs e)
		{
			this.btnPerform.Enabled = false;

			try
			{
				DirectoryInfo targetFolder = new DirectoryInfo(this.txtRootFolder.Text);
				if (targetFolder.Exists == false)
				{
					return;
				}

				FileInfo[] expectedFiles = targetFolder.GetFiles(this.txtSearchPattern.Text, SearchOption.AllDirectories);
				if (expectedFiles.Length < 1)
				{
					return;
				}

				// Get the file to process
				List<string> filesToProcess = new List<string>();
				foreach (FileInfo file in expectedFiles)
				{
					if (!file.FullName.EndsWith(".min.js") && !filesToProcess.Contains(file.FullName))
					{
						filesToProcess.Add(file.FullName);
					}
				}

				int successCounter = 0;
				JavaScriptMinifier jsMinifier = new JavaScriptMinifier();
				foreach (string fileName in filesToProcess)
				{
					StringBuilder newFile = new StringBuilder();
					newFile.Append(fileName.Substring(0, fileName.LastIndexOf(".")));
					newFile.Append(".min");
					newFile.Append(fileName.Substring(fileName.LastIndexOf(".")));

					jsMinifier.Minify(fileName, newFile.ToString());
					successCounter++;
				}

				this.lblNbOfProcessedFiles.Text = this.lblNbOfProcessedFiles.Text.Substring(0, this.lblNbOfProcessedFiles.Text.LastIndexOf(":"));
				this.lblNbOfProcessedFiles.Text += ": " + successCounter.ToString();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}

			this.btnPerform.Enabled = true;
		}

		private void btnSelectFolder_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog dialog = new FolderBrowserDialog();
			if (dialog.ShowDialog() == DialogResult.OK)
			{
				this.txtRootFolder.Text = dialog.SelectedPath;
			}
		}
	}
}
